import time
from configparser import ConfigParser

from fastapi import FastAPI, Request

from api import MessageApi
from code import MergePictureText, MergePicture, MorningPaper
from models import AllReport, PostType
from models import MessageReport
from utils import print_blue, print_yellow, print_red

app = FastAPI()


@app.get("/")
async def root_get():
    return {"message": "Hello World"}


@app.post("/")
async def root_post(request: Request):
    try:
        print_blue('-' * 80)
        print_blue('StartTime:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        config = ConfigParser()
        res = config.read('./config.env')
        if res:
            monitor_host = config.get('MONITOR_SERVER', 'HOST')
            monitor_port = config.get('MONITOR_SERVER', 'PORT')
            print_yellow(f'ListeningConfiguration： HOST: {monitor_host} PORT: {monitor_port}')
            message_api = MessageApi(monitor_host, int(monitor_port))
            body = await request.json()
            event = AllReport(**body)
            if event.post_type == PostType.message:
                message_report = MessageReport(**body)
                print_blue('Message:', message_report.model_dump_json())
                # 文图合并
                MergePictureText(message_report, message_api)
                # 图片拼接
                MergePicture(message_report, message_api)
                # 早报
                MorningPaper(message_report, message_api)
            elif event.post_type == PostType.message_sent:
                print('message_sent:', body)
            elif event.post_type == PostType.notice:
                print('notice:', body)
            elif event.post_type == PostType.request:
                print('request:', body)
            elif event.post_type == PostType.meta_event:
                print('meta_event:', body)
        else:
            print('ConfigurationFileNotFound: {config.env}')
        print_blue('EndTime:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        print_blue('-' * 80)
    except Exception as e:
        print_red('ErrorMessage:', e)


if __name__ == '__main__':
    import uvicorn

    try:
        config = ConfigParser()
        res = config.read('./config.env')
        if res:
            reporting_host = config.get('REPORT_SERVER', 'HOST')
            reporting_port = config.get('REPORT_SERVER', 'PORT')
            print_blue(f'ReportConfiguration: HOST: {reporting_host} PORT: {reporting_port}')
            # uvicorn.run(app='main:app', host=reporting_host, port=int(reporting_port), reload=True, reload_delay=1)
            uvicorn.run(app='main:app', host=reporting_host, port=int(reporting_port))
        else:
            print_red('ConfigurationFileNotFound: {config.env}')
    except Exception as e:
        print_red('ErrorMessage:', e)
